<template>
  <div class="app-container">
    <div>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="认证名称" required>
          <el-input v-model="form.name" style="width: 40%">
          </el-input>
        </el-form-item>
        <el-form-item label="所属项目" required>
          <el-select
            v-model="form.belong_project"
            filterable
            :disabled="operation_type === 1 ? true:false"
            placeholder="请选择项目"
            @change="fetchProjectData">
            <el-option
              v-for="item in project_options"
              :key="item.id"
              :label="item.project_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="认证方式" required>
              <el-select v-model="form.auth_type" filterable placeholder="请选择认证方式">
                <el-option
                  v-for="items in auth_options"
                    :key="items.label"
                    :label="items.label"
                    :value="items.value">
                </el-option>
              </el-select>
        </el-form-item>
        <div v-if="form.auth_type === 'Basic Authentication'">
          <el-form-item label="认证地址" required>
            <el-input v-model="form.auth_url" style="width: 40%">
            </el-input>
          </el-form-item>
          <el-form-item label="用户账号" required>
            <el-input v-model="form.user_name" style="width: 40%">
            </el-input>
          </el-form-item>
          <el-form-item label="用户密码" required>
            <el-input v-model="form.password" style="width: 40%">
            </el-input>
          </el-form-item>
        </div>
        <div v-else="form.auth_type === 'Custom Authentication'">
          <el-form-item label="接口信息" required>
              <el-row>
                <el-col :span="12">
                  <el-input placeholder="优先级：完整URL > @@@key@@@ > 空" v-model="form.request.request.url">
                    <template slot="prepend">URL</template>
                  </el-input>
                </el-col>
                <el-col :span="1">
                  <el-tooltip class="item" effect="dark">
                    <div slot="content">
                        URL的内容，决定了认证URL的优先级：<br/>
                        1.完整URL :如果完整URL,直接作为认证URL<br/>
                        2.@@@key@@@ :变量样式，使用配置信息-variables中key,对应的value值,为认证URL)<br/>
                        3.空：直接使用配置信息-url中的auth_url,为认证URL<br/>
                        认证URL，会作为获取token时使用的认证URL<br/>
                      </div>
                    <i class="el-icon-info" style="font-size: 20px; font-weight: 500; top: 50%" />
                  </el-tooltip>
                </el-col>
                <el-col :span="2">
                  <el-select
                      ref="request_method"
                      v-model="form.request.request.method"
                      placeholder="Select Method"
                      @change="methodChange">
                    <el-option label="POST" value="POST"/>
                    <el-option label="GET" value="GET"/>
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <el-select
                      ref="request_method_get"
                      v-model="form.request.request.type"
                      placeholder="Select Data type"
                      @change="typeChange">
                      <el-option label="params" value="params" v-if="form.request.request.method === 'GET'" />
                      <el-option label="data" value="data" v-if="form.request.request.method === 'POST'"/>
                      <el-option label="json" value="json" v-if="form.request.request.method === 'POST'"/>
                  </el-select>
                </el-col>
              </el-row>

            <div v-if="form.request.request.type === 'params'" key="params" style="margin-top: 15px" >
                <tableSelect
                  ref="TableSelectParams"
                  :table-type="'Params'"
                  v-if="getinfo_flag || !operation_type"
                  :datas-text.sync="form.request.request.content"
                  @changeList="changeParamsLists"
                />
              </div>
            <div v-else-if="form.request.request.type === 'data'" key="data" style="margin-top: 15px">
                <tableSelect
                  ref="TableSelectData"
                  :table-type="'Data'"
                  v-if="getinfo_flag || !operation_type"
                  :datas-text.sync="form.request.request.content"
                  @changeList="changeDataLists"
                />
            </div>
            <div v-else style="margin-top: 15px">
              <div v-if="getinfo_flag || !operation_type">
                <b-code-editor
                  ref="editor"
                  v-model="form.request.request.content"
                  theme="rubyblue"
                  :auto-format="true"
                  :indent-unit="4"
                  :smart-indent="true"
                  :line-wrap="true"
                />
             </div>
                <el-button
                    type="success"
                    @click="$refs['editor'].formatCode()">格式化JSON
                </el-button>
                <el-button
                    type="success"
                    @click="validateJSON">校验JSON
                </el-button>
          </div>
              <tableSelect
                ref="TableSelect"
                :table-type="'Headers'"
                v-if="getinfo_flag || !operation_type"
                :datas-text.sync="form.request.request.headers"
                @changeList="changeHeadersLists"
                style="margin-top: 15px"
              />
          </el-form-item>
          <el-form-item label="提取token" required>
            <el-input v-model="form.request.extract" placeholder="请输入response中要提取token的key"  style="width: 40%" >
            </el-input>
          </el-form-item>
          <el-form-item label="token赋值" required>
            <el-input v-model="form.request.header_token_key" placeholder="请输入token赋值到关联接口请求头中的key"  style="width: 40%" >
            </el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div style="text-align: center">
      <el-button type="success" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>
    <br>
    <br>
  </div>
</template>

<script>
import { getProjectSumList } from '@/api/project/table'
import { createAuth, getAuth, updateAuth } from '@/api/test_auth/table'
import tableSelect from '@/components/tableSelect'

const jsonData = '{"key": "value"}'
export default {
  components: {
    tableSelect
  },
  data() {
    return {
        operation_type: 0, // 0:create 1:update 2:copy
        authID: '',
        getinfo_flag: false,
        form: {
        name: '',
        user_name: '',
        auth_url: '',
        password: '',
        belong_project: '',
        auth_type: 'Custom Authentication',
        author: '',
        request: {
            request: {
              url: '',
              method: 'POST',
              type: 'data',
              content: [],
              headers: []
          },
            extract: '',
            header_token_key: ''
        },
      },
        auth_options: [ // key类型选项
        {
          label: 'Custom Authentication',
          value: 'Custom Authentication'
        },
        {
         label: 'Basic Authentication',
         value: 'Basic Authentication'
        }
      ],
      project_options: []
    }
  },

  created() {
    this.operation_type = this.$route.query.operation_type || 0
    this.authID = this.$route.query.id || ''

    if (this.operation_type !== 0) {
      this.getParams() //编辑或复制
      this.fetchProjectData()
    } else {
      this.fetchProjectData()//新增
    }
  },

  methods: {
    fetchProjectData() {
      getProjectSumList().then(response => {
        this.project_options = response.results
      })
    },

    getParams() {
      var params = {}
      params['id'] = this.authID
      return new Promise((resolve, reject) => {
        getAuth(params).then(response => {
          this.form = response.data
          this.getinfo_flag = response.success
        }).catch(e =>{
          reject(e)
        })
      })
    },

    onSubmit() {
      if (this.operation_type.toString() === '1') {
        updateAuth(this.form).then(response => {
          if (response.status === '000000') return
          this.$message.success('更新成功')
          this.$router.replace(`/test_auth/auth_list`)
        })
      } else {
        createAuth(this.form).then((response) => {
          console.log(response.msg)
          if (response.status === '000000') return
          this.$message.success('创建成功')
          this.$router.replace(`/test_auth/auth_list`)
        })
      }
    },
    handleClick(tab, event) {
      console.log(tab, event)
      console.log(this.activeTab)
    },

    onCancel() {
      this.$confirm('此操作将退出出编辑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.replace(`/test_auth/auth_list`)
        this.$message({
          type: 'success',
          message: '退出成功!',
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        })
      })
    },

    validateJSON() {
      if (this.form.request.request.type === 'json') {
        var str = this.form.request.request.content
        if (typeof str == 'string') {
          try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
              this.$message.info(`json格式正确`)
              return true
            } else {
              this.$message.error(`json格式错误,请修正后再提交`)
              return false
            }
          } catch (e) {
            this.$message.error(`json格式错误,请修正后再提交`)
            return false
          }
        } else if (typeof str == 'object' && str) {
          this.$message.error(`json格式错误,请修正后再提交`)
          return true
        }
      }
    },

    methodChange() {
      console.log("Request Method : " + this.form.request.request.method)
      if (this.form.request.request.method === 'GET') {
        this.$set(this.form.request.request, "type", 'params')
      }
      if (this.form.request.request.method === 'POST') {
        this.$set(this.form.request.request, "type", 'data')
      }
    },

    typeChange() {
      console.log("Request Type : " + this.form.request.request.type)
      if (this.form.request.request.type === 'json') {
        console.log("Request content : " + this.form.request.request)
        // this.form.request.request.push({'json': jsonData})
        this.form.request.request.content = jsonData
      }
      if (this.form.request.request.type === 'data') {
        // this.form.request.request.push({'data': []})
        this.form.request.request.content = []
      }
      if (this.form.request.request.type === 'params') {
        // this.form.request.request.push({'params': []})
        this.form.request.request.content = []
      }
    },

    changeDataLists: function(obj) {
      this.form.request.request.content = obj.list
    },
    changeParamsLists: function(obj) {
      this.form.request.request.content = obj.list
    },
    changeHeadersLists: function(obj) {
      this.form.request.request.headers = obj.list
    },
  }
}
</script>

<style scoped lang="scss">
  .line {
    text-align: center;
  }

  .el-form-item{
      margin-bottom: 16px;
  }

  .flex-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-content: center;

  .inline-box {
    display: inline-block;
    width: 350px;

    &:last-child {
      width: 500px;
    }
  }

  > span {
    font-size: 30px;
    line-height: 290px;
  }
}

</style>

